package states

import (
	"go_server/game_server/api/service/bag"
	"go_server/game_server/dao/count_down_dao"
	"go_server/game_server/dataconfig/config_manager"
	"go_server/game_server/event_manager"
	"go_server/game_server/event_manager/event_data/event_impl"
	"go_server/game_server/protocol/pb"
	"go_server/game_server/util"
	"go_server/game_server/world_manager"
	"go_server/zinx/ziface"
	"go_server/zinx/zlog"
	"go_server/zinx/znet"
)

type CollectFoodApi struct {
	znet.BaseRouter
}

// 收集食物
func (*CollectFoodApi) Handle(request ziface.IRequest) {
	msg := &pb.CollectFoodC2S{}
	if !util.PBParseRet(request, msg) {
		return
	}

	conn := request.GetConnection()
	roleId := ServiceObj.GetRoleId(request)

	config := config_manager.GettableMap3DConfigSheetSundriesById(msg.FoodId)
	if config.Reward == nil || config.ClickType != CLICK_TYPE2 {
		zlog.Errorf("收集食物配置奖励不存在")
		world_manager.WorldMgrObj.SendClientErrMsg(roleId, request, pb.ErrorCodeManager_FOOD_CONFIG_UNFIND, nil)
		return
	}

	fields := []string{"collect_food_list"}
	row := count_down_dao.GetCountDownByRoleId(roleId, fields)

	collectFoodList := make([]int32, 0)
	if row != nil && row.CollectFoodList != nil {
		collectFoodList = row.CollectFoodList
	}

	var update = true

	if len(collectFoodList) > 0 {
		eventSet := util.NewSet[int32]()
		eventSet.AddValue(collectFoodList)
		if !eventSet.Contains(msg.FoodId) {
			collectFoodList = append(collectFoodList, msg.FoodId)
		} else {
			update = false // 食物已收集
		}
	} else {
		collectFoodList = append(collectFoodList, msg.FoodId)
	}

	res := &pb.CollectFoodS2C{
		CollectFoodList: collectFoodList,
	}
	conn.SendBuffPBMsg(uint32(pb.ProtocolManager_CollectFood), res)

	if update {
		countDown := count_down_dao.CountDown{
			RoleId:          roleId,
			CollectFoodList: collectFoodList,
		}
		count_down_dao.UpdateCountDown(&countDown, fields)

		// 发送奖励
		bag.AddItemArrayInt32(roleId, config.Reward)

		// 创建收集食物事件
		event_manager.EventManagerObj.FireEventData(event_impl.NewCollectFoodEvent(conn))
	}
}
